package com.simple.core.exception;

import cn.hutool.core.collection.CollUtil;
import com.simple.core.dto.Response;
import com.simple.core.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author FanXing
 * @date 2022年11月07日 14:29
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException:", e);
        List<ObjectError> objectErrors = e.getBindingResult().getAllErrors();
        String msg = "参数校验异常";
        if (CollUtil.isNotEmpty(objectErrors)) {
            msg = objectErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
        }
        return Response.error(msg);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Response<String> constraintViolationExceptionHandler(ConstraintViolationException e) {
        log.error("ConstraintViolationException:", e);
        Set<ConstraintViolation<?>> objectErrors = e.getConstraintViolations();
        String msg = "参数校验异常";
        if (CollUtil.isNotEmpty(objectErrors)) {
            msg = objectErrors.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
        }
        return Response.error(msg);
    }

    @ExceptionHandler(BizException.class)
    public Response<String> bizExceptionHandler(BizException e) {
        log.error("BizException: ", e);
        return Response.error(e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public Response<String> nullPointExceptionHandler(NullPointerException e) {
        log.error("NullPointException:", e);
        return Response.error(ResponseCode.FAIL.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Response<String> exceptionHandler(Exception e) {
        log.error("error", e);
        return Response.error(ResponseCode.FAIL.getMessage());
    }

}
